package com.uobgroup.ews.uam.web.validation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.uobgroup.ews.uam.core.domain.ReferenceType;
import com.uobgroup.ews.uam.core.service.ReferenceTypeService;

@Component
public class ReferenceTypeValidator implements Validator {

   @Autowired
   ReferenceTypeService referenceTypeService;
   
   @Autowired
   private ReloadableResourceBundleMessageSource messageSource;
   
   @Override
   public boolean supports(Class<?> clazz) {
      return ReferenceType.class.getName().equals(clazz.getName()) || String.class.getName().equals(clazz.getName());
   }

   @Override
   public void validate(Object target, Errors errors) {
      if(target instanceof ReferenceType){
         ReferenceType referenceType = (ReferenceType)target;
         
         Long id = referenceType.getId();
         String name = referenceType.getName();
         String code = referenceType.getCode();
         
         if (null == name || name.isEmpty()) {
            errors.rejectValue("name", "field_mandatory", new String[] { messageSource.getMessage("label_com_uobgroup_ews_uam_core_domain_referencetype_name", null, "", null) }, null);
         }
         if (null == code || code.isEmpty()) {
            errors.rejectValue("code", "field_mandatory", new String[] { messageSource.getMessage("label_com_uobgroup_ews_uam_core_domain_referencetype_code", null, "", null) }, null);
         }
         if (null != name && !name.isEmpty() && name.length() > 255) {
            errors.rejectValue("name", "field_maxLength");
         }
         if (null != code && !code.isEmpty() && code.length() > 64) {
            errors.rejectValue("code", "field_maxLength");
         }
         if (null == id || id.longValue() == 0 ) {
            if (null != name && !name.isEmpty() && null != referenceTypeService.findReferenceTypeByName(name)) {
               errors.rejectValue("name", "field_unique", new String[] { name }, null);
            }
            
            if (null != code && !code.isEmpty() && null != referenceTypeService.findReferenceTypeByCode(code)) {
               errors.rejectValue("code", "field_unique", new String[] { code }, null);
            }
         } else {
            if (null != name && !name.isEmpty() && null != referenceTypeService.findReferenceTypeThatHasNameAndNotHasId(name, id)) {
               errors.rejectValue("name", "field_unique", new String[] { name }, null);
            }
            
            if (null != code && !code.isEmpty() && null != referenceTypeService.findReferenceTypeThatHasCodeAndNotHasId(code, id)) {
               errors.rejectValue("code", "field_unique", new String[] { code }, null);
            }
         }
      }
   }
}
